<template>
  <div class="mod-config">
    <el-form>
      <el-form-item>
        <el-button-group>
          <el-button size="mini" v-if="isAuth('sale:print:save')" type="primary"
            @click="addOrUpdateHandle()" icon="el-icon-plus">新增</el-button>
          <el-button size="mini" v-if="isAuth('sale:print:delete')" type="danger"
            @click="deleteHandle()" icon="el-icon-delete" :disabled="dataListSelections.length <= 0">删除</el-button>
        </el-button-group>
        <el-button-group>
          <el-button size="mini" v-if="isAuth('sale:print:info')" :disabled="dataListSelections.length <= 0" type="qblue" @click="printNoBackground()"
            class="iconfont icon-print">打印(无背景)</el-button>
          <el-button size="mini" v-if="isAuth('sale:print:info')" :disabled="dataListSelections.length <= 0" type="qblue" @click="printHasBackground()"
              class="iconfont icon-print">打印(带背景)</el-button>
        </el-button-group>
        <el-button size="mini" v-if="isAuth('sale:print:import')" :disabled="dataListSelections.length <= 0" type="success" @click="importData()"
          class="iconfont icon-skip">导入</el-button>
      </el-form-item>
      <el-form-item>
        <el-dialog title="导入数据" :visible.sync="upload.open" width="400px" append-to-body :close-on-click-modal="false">
          <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
            :before-upload="beforeUpload" :action="upload.url" :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false"
            :file-list="excelList" :on-remove="onRemoveDr" :on-change="onChangeDr" drag>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
            <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
          </el-upload>
          <el-button size="mini" type="success" @click="downloadImportTemplate">下载模板</el-button>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitFileForm">导 入</el-button>
            <el-button @click="cancelFileForm">取 消</el-button>
          </div>
        </el-dialog>
      </el-form-item>
    </el-form>
    <el-table :data="dataList" size="mini" v-loading="dataListLoading" @selection-change="selectionChangeHandle"
      style="width: 100%;"
      :header-cell-style="{ background: '#fcfcfc', color: '#606266', height:'36px'}">
      <el-table-column type="selection" header-align="center" align="center" width="50">
      </el-table-column>
      <el-table-column prop="productCode" header-align="center" align="center" label="产品编号">
      </el-table-column>
      <el-table-column prop="productName" header-align="center" align="center" label="产品名称" width="150" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="genericName" header-align="center" align="center" label="通用名" v-if="false">
      </el-table-column>
      <el-table-column prop="standard" header-align="center" align="center" label="规格">
      </el-table-column>
      <el-table-column prop="unit" header-align="center" align="center" label="单位">
      </el-table-column>
      <el-table-column prop="barCode" header-align="center" align="center" label="条形码">
      </el-table-column>
      <el-table-column prop="producingArea" header-align="center" align="center" label="产地" width="150" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="produceFactory" header-align="center" align="center" label="生产单位" width="150" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="approvalNo" header-align="center" align="center" label="批准文号" width="130" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="dosageForm" header-align="center" align="center" label="剂型">
      </el-table-column>
      <el-table-column prop="produceDate" header-align="center" align="center" label="生产日期" v-if="false">
      </el-table-column>
      <el-table-column prop="expiryDate" header-align="center" align="center" label="有效期" v-if="false">
      </el-table-column>
      <el-table-column prop="salePrice" header-align="center" align="center" label="销售价">
      </el-table-column>
      <el-table-column prop="memberPrice" header-align="center" align="center" label="会员价">
      </el-table-column>
      <el-table-column fixed="right" header-align="center" align="center" width="100" label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="text" v-if="isAuth('sale:saleproductsplitdetail:delete')"
            @click="deleteHandle(scope.row.detailId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
  </div>
</template>

<script>
  import AddOrUpdate from './printproductsing-add-or-update'
  import {downLoadFile, hasRole  } from '@/utils/myUtil.js'
  import {Loading  } from "element-ui"
  export default {
    data() {
      return {
        dataForm: {
          key: ''
        },
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        showInput: "",
        oldData: {},
        currentData: {},
        //导入
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "导入药品数据",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          // updateSupport: 0,
          // 设置上传的请求头部
          // 上传的地址
          url: `${window.SITE_CONFIG.baseUrl}/sale/saleproductsplitdetail/importData`
        },
        //上传的文件
        excelList: [],
      }
    },
    components: {
      AddOrUpdate
    },
    activated() {
      this.getDataList()
    },
    methods: {
      // 获取数据列表
      async getDataList() {
        this.dataListLoading = true
        let printDatas = JSON.parse(sessionStorage.getItem("printDatas"))
        if(printDatas && printDatas.length > 0){
          this.dataList = printDatas
        }
        this.dataListLoading = false
      },
      // 每页数
      sizeChangeHandle(val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle(val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle(val) {
        this.dataListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle(id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id)
        })
      },
      // 删除
      deleteHandle(id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.productId
        })
        this.dataList.forEach((item, index, arr) => {
          if(ids.indexOf(item.productId) != -1 ){
            arr.splice(index, 1)
          }
        })
        sessionStorage.setItem("printDatas", JSON.stringify(this.dataList))
      },
      printNoBackground(){
        let products = JSON.stringify(this.dataListSelections)
        this.$router.push({name:'printnoback',query: {products}})
      },
      printHasBackground(){
        let products = JSON.stringify(this.dataListSelections)
        this.$router.push({name:'printhasback',query: {products}})
      },
      async exportData() {
        const res = await this.$http({
          url: `/sale/saleproductsplitdetail/exportData`,
          method: 'get',
          responseType: 'blob',
          params: this.$http.adornParams()
        });
        downLoadFile(res)
      },
      beforeUpload(file) {
        //截取文件后缀名
        const fileName = file.name.substring(file.name.lastIndexOf('.'));
        if (fileName.toLowerCase() != '.xls' && fileName.toLowerCase() != '.xlsx') {
          this.$message.error('文件必须为.xls或xlsx类型');
          this.fileList = [];
          return false;
        };
        //读取文件大小
        var fileSize = file.size;
        if (fileSize > 3249576) {
          this.uploadShowDialog = false;
          this.$message({
            type: 'error',
            showClose: true,
            duration: 3000,
            message: '文件不能大于3M!'
          });
          return false;
        }
      },
      // excel表上传
      handleUploadChange(file, fileList) {
        if (fileList.length > 0) {
          // 这一步，是展示最后一次选择的文件
          this.fileList = [fileList[fileList.length - 1]];
        }
      },
      //导入按钮
      handleImport() {
        this.upload.open = true;
      },
      //导入提交
      async submitFileForm() {
        if (this.excelList.length === 0) {
          this.$message.warning("请选择文件");
          return;
        }
        if (this.excelList.length > 1) {
          this.$message.warning("每次只能提交一个文件");
          return;
        }
        let formData = new FormData();
        this.excelList.forEach((item) => {
          formData.append("file", item.raw);
        });
        let loadingInstance = Loading.service({
          lock: true, //lock的修改符--默认是false
          text: "导入中", //显示在加载图标下方的加载文案
          spinner: "el-icon-loading", //自定义加载图标类名
          background: "rgba(0, 0, 0, 0.7)", //遮罩层颜色
          target: document.querySelector("#futureTransferDialog"), //loadin覆盖的dom元素节点
        });
        const res = await this.$http({
          url: this.upload.url,
          method: 'post',
          data: formData
        })
        let data = res.data
        if (data && data.code === 0) {
          loadingInstance.close();
          this.$message({
            type: "success",
            message: "导入成功!",
          });
          this.getDataList();
        }
        this.excelList = [];
        this.upload.open = false;
        loadingInstance.close();
        this.dataListLoading = false
      },
      //下载导入模板
      downloadImportTemplate() {
        window.location.href = "http://file.asdzy.com/upload/files/film/品牌模板.xlsx"
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.excelList = fileList;
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      onChangeDr(file, fileList) {
        this.excelList = fileList;
      },
      onRemoveDr(file, fileList) {
        this.excelList = fileList;
      },
      cancelFileForm() {
        this.upload.open = false
        this.excelList = [];
      },
    },

    directives: {
      // 通过自定义指令实现的表单自动获得光标的操作
      focus: {
        inserted: function(el) {
          if (el.tagName.toLocaleLowerCase() == "input") {
            el.focus()
          } else {
            if (el.getElementsByTagName("input")) {
              el.getElementsByTagName("input")[0].focus()
            }
          }
          el.focus()
        }
      },
      focusTextarea: {
        inserted: function(el) {
          if (el.tagName.toLocaleLowerCase() == "textarea") {
            el.focus()
          } else {
            if (el.getElementsByTagName("textarea")) {
              el.getElementsByTagName("textarea")[0].focus()
            }
          }
          el.focus()
        }
      }
    },
  }
</script>
